<template>
  <div class="min-h-screen video-detail-page pt-0 md:pt-45px">
    <!-- 播放器区域 -->
    <div class="relative bg-black">
      <!-- 播放器容器 -->
      <div class="player-container aspect-video w-full max-w-[1920px] mx-auto">
        <div v-if="currentVideoUrl && currentPlayer" class="w-full h-full">

          <!-- iframe播放器 -->
          <iframe
            v-if="currentPlayer.playerType === 'iframe'"
            :src="getPlayerUrl(currentVideoUrl, currentPlayer)"
            class="w-full h-full"
            frameborder="0"
            allowfullscreen
            allow="autoplay; fullscreen"
          ></iframe>

          <!-- 其他播放器类型可以在这里扩展 -->
          <video
            v-else-if="currentPlayer.playerType === 'video'"
            :src="currentVideoUrl"
            class="w-full h-full"
            controls
            autoplay
          ></video>

          <!-- 默认提示 -->
          <div v-else class="w-full h-full flex items-center justify-center text-white">
            <p>不支持的播放器类型：{{ currentPlayer.playerType }}</p>
          </div>
        </div>

        <!-- 加载中或无资源 -->
        <div v-else class="w-full h-full flex items-center justify-center bg-gray-900">
          <div class="text-center text-white">
            <el-icon v-if="!playList.length" :size="80" color="#999">
              <VideoPlay />
            </el-icon>
            <p class="mt-4">{{ playList.length ? '加载中...' : '暂无可播放资源' }}</p>
          </div>
        </div>
      </div>

      <!-- 播放器下方信息栏 -->
      <div class="container mx-auto px-4 py-4">
        <div class="flex flex-col md:flex-row gap-4 items-start md:items-center justify-between">
          <div class="flex-1">
            <h1 class="text-2xl md:text-3xl font-bold text-white mb-2">{{ movie?.title }}</h1>
            <div class="flex flex-wrap gap-4 text-sm text-gray-300">
              <span v-if="movie?.movieRate?.rate" class="flex items-center">
                <el-icon class="mr-1" color="#F7BA2A">
                  <StarFilled />
                </el-icon>
                {{ movie.movieRate.rate.toFixed(1) }}
              </span>
              <span>{{ movie?.year }}年</span>
              <span v-if="movie?.area">{{ movie.area }}</span>
              <span v-if="movie?.duration">{{ movie.duration }}分钟</span>
              <span v-if="currentPlayNote" class="text-primary">
                正在播放：{{ currentPlayNote }}
              </span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex flex-wrap gap-3">
            <el-button
              size="large"
              @click="toggleCollection"
            >
              <el-icon class="mr-2" :color="isCollected ? '#F7BA2A' : ''">
                <component :is="isCollected ? StarFilled : Star" />
              </el-icon>
              {{ isCollected ? '已收藏' : '收藏' }}
            </el-button>

            <el-button
              size="large"
              @click="shareMovie"
              :icon="Share"
            >
              分享
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 详细信息 -->
    <div class="container mx-auto px-4 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧主要内容 -->
        <div class="lg:col-span-2 space-y-8">
          <!-- 播放源选择和剧集列表 -->
          <el-card v-if="playList && playList.length > 0" class="detail-card">
            <template #header>
              <div class="flex items-center justify-between">
                <h2 class="text-xl font-semibold">选集</h2>
                <!-- 播放源切换 -->
                <div v-if="playList.length > 1" class="flex gap-2">
                  <el-radio-group v-model="currentPlayFrom" size="small">
                    <el-radio-button
                      v-for="play in playList"
                      :key="play.playFrom"
                      :label="play.playFrom"
                    >
                      {{ play.playNote || play.playFrom }}
                    </el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </template>

            <!-- 当前播放源的剧集列表 -->
            <div v-if="currentPlayUrls && currentPlayUrls.length > 0" class="space-y-4">
              <div class="grid grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
                <el-button
                  v-for="(episode, index) in currentPlayUrls"
                  :key="episode.resourceId"
                  :type="currentEpisode === index ? 'primary' : 'default'"
                  size="small"
                  @click="selectEpisode(episode, index)"
                >
                  {{ episode.title || `第${index + 1}集` }}
                </el-button>
              </div>

              <!-- 播放器信息 -->
              <div v-if="currentPlayer" class="text-sm text-gray-400 mt-2">
                <span>播放器：{{ currentPlayer.playerName || currentPlayFrom }}</span>
              </div>
            </div>

            <div v-else class="text-center py-8 text-gray-400">
              该播放源暂无可用剧集
            </div>
          </el-card>

          <!-- 简介 -->
          <el-card class="detail-card">
            <template #header>
              <h2 class="text-xl font-semibold">剧情简介</h2>
            </template>
            <div class="text-gray-300 leading-relaxed summary-content" v-html="movie?.summary"></div>
          </el-card>

          <!-- 演职人员 -->
          <el-card class="detail-card">
            <template #header>
              <h2 class="text-xl font-semibold">演职人员</h2>
            </template>

            <!--演员卡片展示 -->
            <div v-if="movie?.casts && movie.casts.length > 0" class="mb-6">
              <div class="grid grid-cols-3 md:grid-cols-4 xl:grid-cols-6 gap-15px md:gap-20px">
                <div v-for="cast in movie.casts" :key="cast.castId" class="text-12px text-center">
                  <NuxtImg
                    v-if="cast.actor?.avatar"
                    :src="cast.actor.avatar"
                    :alt="cast.actor.name"
                    size="150px"
                    format="webp"
                    loading="lazy"
                    class="w-full aspect-3/4 object-cover mb-6px rounded"
                  />
                  <div v-else class="w-full aspect-3/4 bg-gray-700 mb-6px rounded flex items-center justify-center">
                    <el-icon :size="24" color="#999">
                      <User />
                    </el-icon>
                  </div>
                  <p class="text-white text-sm">{{ cast.actor?.name || '-' }}</p>
                  <p v-if="cast.role" class="text-gray-400 text-xs mt-1">饰 {{ cast.role }}</p>
                  <p v-else-if="cast.profession?.name" class="text-gray-400 text-xs mt-1">
                    {{ cast.profession.name }}
                  </p>
                </div>
              </div>
            </div>

            <div v-else class="space-y-4 text-gray-300">
              <!-- 导演 -->
              <div v-if="movie?.directorText" class="info-row">
                <span class="text-gray-400 font-medium w-16 inline-block">导演：</span>
                <span>{{ movie.directorText }}</span>
              </div>

              <!-- 编剧 -->
              <div v-if="movie?.writerText" class="info-row">
                <span class="text-gray-400 font-medium w-16 inline-block">编剧：</span>
                <span>{{ movie.writerText }}</span>
              </div>

              <!-- 主演 -->
              <div v-if="movie?.actorText" class="info-row">
                <span class="text-gray-400 font-medium w-16 inline-block mb-2 align-top">主演：</span>
                <div class="inline-block flex-1">
                  <div class="flex flex-wrap gap-2">
                    <span
                      v-for="(actor, index) in parseActors(movie.actorText)"
                      :key="index"
                      class="actor-tag"
                    >
                      {{ actor }}
                    </span>
                  </div>
                </div>
              </div>

              <!-- 制片人 -->
              <div v-if="movie?.producerText" class="info-row">
                <span class="text-gray-400 font-medium w-16 inline-block">制片：</span>
                <span>{{ movie.producerText }}</span>
              </div>
            </div>
          </el-card>

          <!-- 评论区 -->
          <el-card class="detail-card">
            <template #header>
              <h2 class="text-xl font-semibold">评论</h2>
            </template>

            <!-- 发表评论 -->
            <div v-if="isLoggedIn" class="mb-6">
              <el-input
                v-model="commentContent"
                type="textarea"
                placeholder="写下你的评论..."
                :rows="3"
                class="mb-3"
              />
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-2">
                  <span class="text-sm text-gray-400">评分：</span>
                  <el-rate v-model="commentRating" :max="5" size="large" />
                </div>
                <el-button type="primary" @click="submitComment">发表评论</el-button>
              </div>
            </div>
            <div v-else class="mb-6 text-center py-4 bg-gray-900 rounded">
              <p class="text-gray-400 mb-2">登录后才能发表评论</p>
              <el-button size="small" @click="navigateTo('/login')">立即登录</el-button>
            </div>

            <!-- 评论列表 -->
            <div class="space-y-4">
              <div v-for="comment in comments" :key="comment.commentId" class="border-b border-gray-700 pb-4">
                <div class="flex items-start gap-3">
                  <el-avatar :src="comment.userAvatar" :alt="comment.userName" :size="40" />
                  <div class="flex-1">
                    <div class="flex items-center gap-2 mb-1">
                      <span class="font-medium text-white">{{ comment.userName }}</span>
                      <el-rate
                        v-if="comment.rating"
                        v-model="comment.rating"
                        disabled
                        :max="5"
                        size="small"
                      />
                    </div>
                    <p class="text-gray-300 mb-2">{{ comment.content }}</p>
                    <div class="flex items-center gap-4 text-sm text-gray-400">
                      <span>{{ formatDate(comment.createTime) }}</span>
                      <el-button text size="small" @click="likeComment(comment)">
                        <el-icon class="mr-1">
                          <component :is="comment.isLiked ? StarFilled : Star" />
                        </el-icon>
                        {{ comment.likeCount || 0 }}
                      </el-button>
                      <el-button text size="small">回复</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 加载更多 -->
            <div v-if="commentTotal > comments.length" class="text-center mt-4">
              <el-button @click="loadMoreComments">加载更多评论</el-button>
            </div>
          </el-card>
        </div>

        <!-- 右侧相关推荐 -->
        <div class="space-y-6">
          <el-card class="detail-card">
            <template #header>
              <h2 class="text-xl font-semibold">相关推荐</h2>
            </template>
            <div class="space-y-4">
              <NuxtLink
                v-for="item in relatedMovies"
                :key="item.movieBasicsId"
                :to="`/column/${item.columnValue}/detail/${item.movieBasicsId}`"
                class="flex gap-3 hover:bg-gray-700 p-2 rounded transition-colors"
              >
                <NuxtImg
                  v-if="item.poster"
                  :src="item.poster"
                  :alt="item.title"
                  size="100px"
                  format="webp"
                  loading="lazy"
                  class="w-20 h-28 rounded object-cover"
                />
                <div v-else class="w-20 h-28 bg-gray-700 rounded flex items-center justify-center">
                  <el-icon :size="24" color="#999">
                    <Picture />
                  </el-icon>
                </div>
                <div class="flex-1">
                  <h3 class="font-medium line-clamp-1 text-white">{{ item.title }}</h3>
                  <p class="text-sm text-gray-400 line-clamp-2 mt-1">{{ item.blurb }}</p>
                  <div class="flex items-center gap-2 mt-2 text-sm text-gray-400">
                    <span v-if="item.movieRate?.rate" class="flex items-center">
                      <el-icon class="mr-1" color="#F7BA2A">
                        <StarFilled />
                      </el-icon>
                      {{ item.movieRate.rate.toFixed(1) }}
                    </span>
                    <span>{{ item.year }}</span>
                  </div>
                </div>
              </NuxtLink>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { StarFilled, Star, VideoPlay, Share, Picture, User } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 获取参数
const movieBasicsId = computed(() => Number(route.params.id))
const columnValue = computed(() => route.params.columnValue as string)

// 状态
const currentEpisode = ref(0)
const currentVideoUrl = ref('')  // 当前播放的视频URL
const isCollected = ref(false)
const commentContent = ref('')
const commentRating = ref(5)
const commentPage = ref(1)
const commentTotal = ref(0)
const movie = ref<any>(null)
const playList = ref<any[]>([])  // 按播放源分组的播放列表
const currentPlayFrom = ref('')  // 当前选中的播放源
const comments = ref<any[]>([])
const relatedMovies = ref<any[]>([])

// 获取影片详情（包含按播放源分组的播放列表）
const getMovieDetail = async () => {
  try {
    const data: any = await $fetch(`/dev-api/app/movieapp/${movieBasicsId.value}`)

    // 新API返回: {code: 200, data: {movie: {...}, playList: [...]}}
    if (data.code === 200 && data.data) {
      movie.value = data.data.movie
      playList.value = data.data.playList || []

      // 默认选择第一个播放源
      if (playList.value.length > 0) {
        currentPlayFrom.value = playList.value[0].playFrom

        // 自动播放第一集
        if (currentPlayUrls.value.length > 0) {
          playVideo(currentPlayUrls.value[0], 0)
        }
      }
    } else if (data.movie && data.playList) {
      // 直接返回数据的情况
      movie.value = data.movie
      playList.value = data.playList || []

      if (playList.value.length > 0) {
        currentPlayFrom.value = playList.value[0].playFrom

        // 自动播放第一集
        if (currentPlayUrls.value.length > 0) {
          playVideo(currentPlayUrls.value[0], 0)
        }
      }
    }
  } catch (error) {
    console.error('获取影片详情失败:', error)
  }
}

// 当前播放源的剧集列表
const currentPlayUrls = computed(() => {
  const currentPlay = playList.value.find(p => p.playFrom === currentPlayFrom.value)
  return currentPlay?.urls || []
})

// 当前播放源的播放器配置
const currentPlayer = computed(() => {
  const currentPlay = playList.value.find(p => p.playFrom === currentPlayFrom.value)
  return currentPlay?.player
})

// 当前播放说明
const currentPlayNote = computed(() => {
  const currentPlay = playList.value.find(p => p.playFrom === currentPlayFrom.value)
  const currentUrl = currentPlayUrls.value[currentEpisode.value]
  return `${currentPlay?.playNote || currentPlayFrom.value} - ${currentUrl?.title || `第${currentEpisode.value + 1}集`}`
})

// 获取播放器URL
const getPlayerUrl = (videoUrl: string, player: any) => {
  if (!player || !player.parseApi) {
    return videoUrl
  }

  // 播放器URL通常需要拼接视频地址
  // 根据播放器配置替换URL中的变量
  let playerUrl = player.parseApi

  // 常见的播放器URL格式：https://player.xxx.com/player.php?url={url}
  if (playerUrl.includes('{url}')) {
    playerUrl = playerUrl.replace('{url}', encodeURIComponent(videoUrl))
  } else if (playerUrl.includes('$url')) {
    playerUrl = playerUrl.replace('$url', encodeURIComponent(videoUrl))
  }else if (playerUrl.includes('?url=')) {
    playerUrl = playerUrl+ encodeURIComponent(videoUrl)
  } else {
    // 如果没有占位符，直接拼接
    const separator = playerUrl.includes('?') ? '&' : '?'
    playerUrl = `${playerUrl}${separator}url=${encodeURIComponent(videoUrl)}`
  }
  debugger
  return playerUrl
}

// 播放视频
const playVideo = (episode: any, index: number) => {
  currentEpisode.value = index
  currentVideoUrl.value = episode.url

  // 记录播放历史
  increaseViewCount()
}

// 切换播放源（监听变化，自动播放第一集）
watch(currentPlayFrom, () => {
  if (currentPlayUrls.value.length > 0) {
    playVideo(currentPlayUrls.value[0], 0)
  }
})

// 获取评论列表（暂时禁用，因为新系统中评论是针对短视频的）
const getCommentList = async () => {
  // 注意：新系统中评论功能是针对短视频的，影视详情暂无评论
  // 如果需要评论功能，可以考虑使用评分系统替代
  comments.value = []
  commentTotal.value = 0
}

// 获取相关推荐
const getRelatedMovies = async () => {
  try {
    const data: any = await $fetch('/dev-api/app/movieapp/recommend', {
      params: {
        columnValue: columnValue.value,
        pageSize: 6
      }
    })

    // /app/** 接口返回 {rows: [], total: number}
    relatedMovies.value = data.rows || []
  } catch (error) {
    console.error('获取相关推荐失败:', error)
  }
}

// 检查收藏状态
const checkCollectionStatus = async () => {
  if (!userStore.isLoggedIn || !userStore.memberUserId) return

  try {
    const data: any = await $fetch(`/dev-api/app/member/collection/check/${userStore.memberUserId}/${movieBasicsId.value}`)

    // 返回 true/false 或 {code, data}
    if (typeof data === 'boolean') {
      isCollected.value = data
    } else if (data.code === 200) {
      isCollected.value = data.data || false
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 选择剧集
const selectEpisode = (episode: any, index: number) => {
  playVideo(episode, index)
}

// 切换收藏
const toggleCollection = async () => {
  if (!isLoggedIn.value || !memberUserId.value) {
    const loginVisible = useLoginVisible()
    loginVisible.value = true
    return
  }

  try {
    if (isCollected.value) {
      // 取消收藏 - 注意：新系统中collection是针对shortId的，这里需要调整
      // 暂时禁用，因为新设计中只支持短视频收藏
      ElMessage.warning('收藏功能开发中...')
    } else {
      // 添加收藏
      const data: any = await $fetch('/dev-api/app/member/collection', {
        method: 'POST',
        body: {
          memberUserId: userStore.memberUserId,
          shortId: null, // 影视收藏待实现
          movieBasicsId: movieBasicsId.value
        }
      })

      if (data.code === 200) {
        isCollected.value = true
        ElMessage.success('收藏成功')
      }
    }
  } catch (error: any) {
    ElMessage.error('操作失败')
  }
}

// 分享
const shareMovie = () => {
  if (navigator.share) {
    navigator.share({
      title: movie.value?.title,
      text: movie.value?.introduction,
      url: window.location.href
    }).catch(() => {
      // 用户取消分享
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href)
    ElMessage.success('链接已复制到剪贴板')
  }
}

// 提交评论（暂时禁用，因为新系统评论是针对短视频的）
const submitComment = async () => {
  ElMessage.info('评论功能开发中，敬请期待')
}

// 点赞评论（暂时禁用）
const likeComment = async (comment: any) => {
  ElMessage.info('点赞功能开发中')
}

// 加载更多评论
const loadMoreComments = async () => {
  commentPage.value++
  await getCommentList()
}

// 增加播放次数
const increaseViewCount = async () => {
  try {
    await $fetch(`/dev-api/app/movieapp/${movieBasicsId.value}/play`, {
      method: 'POST'
    })
  } catch (error) {
    // 静默失败
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

// 解析演员文本（逗号分隔）
const parseActors = (actorText: string) => {
  if (!actorText) return []

  // 按逗号分割，去除空格和空项
  return actorText
    .split(',')
    .map(name => name.trim())
    .filter(name => name && name !== '演员' && name !== '主演')
}

// 初始化数据
onMounted(async () => {
  await Promise.all([
    getMovieDetail(),  // 新API已包含播放列表，无需单独获取
    getCommentList(),
    getRelatedMovies(),
    checkCollectionStatus()
  ])
  increaseViewCount()
})

// SEO设置
useSeoMeta({
  title: movie.value?.title,
  description: movie.value?.introduction,
  ogTitle: movie.value?.title,
  ogDescription: movie.value?.introduction,
  ogImage: movie.value?.poster,
})
</script>

<style scoped lang="scss">
.video-detail-page {
  background-color: #0f0f0f;
  min-height: 100vh;
}

.detail-card {
  background-color: rgba(31, 41, 55, 0.8);
  border: 1px solid rgba(55, 65, 81, 0.5);
}

:deep(.el-card__header) {
  background-color: transparent;
  border-bottom: 1px solid rgba(55, 65, 81, 0.5);
  padding: 16px 20px;
  color: white;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-input__wrapper) {
  background-color: rgba(17, 24, 39, 0.5);
}

:deep(.el-textarea__inner) {
  background-color: rgba(17, 24, 39, 0.5);
  color: white;
}

:deep(.el-button--default) {
  background-color: transparent;
  border-color: rgba(55, 65, 81, 0.5);
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-button--default:hover) {
  background-color: rgba(55, 65, 81, 0.3);
  border-color: #409EFF;
  color: #409EFF;
}

/* 剧情简介HTML内容样式 */
.summary-content {
  :deep(p) {
    margin-bottom: 1rem;
    line-height: 1.8;
  }

  :deep(p:last-child) {
    margin-bottom: 0;
  }

  :deep(br) {
    display: block;
    margin: 0.5rem 0;
    content: "";
  }

  :deep(strong), :deep(b) {
    font-weight: 600;
    color: #fff;
  }

  :deep(em), :deep(i) {
    font-style: italic;
  }

  :deep(a) {
    color: #409EFF;
    text-decoration: none;
    &:hover {
      text-decoration: underline;
    }
  }

  :deep(ul), :deep(ol) {
    margin: 1rem 0;
    padding-left: 2rem;
  }

  :deep(li) {
    margin-bottom: 0.5rem;
  }
}

/* 演职人员信息行 */
.info-row {
  display: flex;
  align-items: flex-start;
  line-height: 1.8;
}

/* 演员标签 */
.actor-tag {
  display: inline-block;
  padding: 6px 14px;
  background: rgba(55, 65, 81, 0.5);
  border: 1px solid rgba(75, 85, 99, 0.6);
  border-radius: 6px;
  font-size: 14px;
  color: #e5e7eb;
  transition: all 0.2s;
  cursor: default;

  &:hover {
    background: rgba(75, 85, 99, 0.6);
    border-color: rgba(107, 114, 128, 0.8);
    transform: translateY(-1px);
  }
}
</style>
